package com.xhwl.logistics.strategy.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhwl.common.dto.cent.vehicle.SupplierConfigDTO;
import com.xhwl.common.enums.vehicle.ParkSupplierEnum;
import com.xhwl.common.enums.vehicle.PassageTypeEnum;
import com.xhwl.common.pojo.cent.device.Device;
import com.xhwl.common.pojo.cent.vehicle.VehcArea;
import com.xhwl.common.pojo.cent.vehicle.VehcParkingLot;
import com.xhwl.common.pojo.cent.vehicle.VehcPassage;
import com.xhwl.logistics.dao.VehcAreaDao;
import com.xhwl.logistics.dao.VehcCardChargeRuleDao;
import com.xhwl.logistics.dao.VehcParkingLotDao;
import com.xhwl.logistics.strategy.InfoSyncSupplierStrategy;
import com.xhwl.logistics.util.HttpUtils;
import com.xhwl.logistics.util.SignUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 信息同步到博思高接口
 * @author: lu.Aaron
 * @create: 2021-06-29 14:38
 **/
//博思高的实现取消，因为实现把厂商配置放在application.yml文件上，目前测试环境(pre)配置信息统一放入配置中心
//@Component
public class InfoSyncBsgoalServiceImpl implements InfoSyncSupplierStrategy {
    @Value("${bsgoal.accessCode}")
    private String accessCode;
    @Value("${bsgoal.signType}")
    private String signType;
    @Value("${bsgoal.companyId}")
    private String companyId;
    @Value("${bsgoal.host}")
    private String host;
    @Value("${bsgoal.appSecret}")
    private String appSecret;
    @Autowired
    private VehcParkingLotDao vehcParkingLotDao;
    @Autowired
    private VehcAreaDao vehcAreaDao;
    @Autowired
    private VehcCardChargeRuleDao vehcCardChargeRuleDao;
    @Override
    public int getParkSupplierId() {
        return ParkSupplierEnum.BSGOAL.supplierId;
    }

    @Override
    public List<VehcParkingLot> getParkingLotList() {
        return null;
    }

/*    @Override
    public VehcParkingLot getParkingLotInfo(ParkingLotDTO parkingLotDTO) {
        parkingLotDTO.setParkingId(parkingLotDTO.getParkId()).setAccessCode(accessCode).setSignType(signType).setCompanyId(companyId).setBusinessCode("ParkinfoGetList_001");
        Map<String, String> map = SignUtils.mapWithSignature(parkingLotDTO, appSecret);
        String json = HttpUtils.post(host, map);
        //解析json
        JSONArray data = JSONObject.parseObject(json).getJSONArray("Data");
        List<Map> maps = JSONArray.parseArray(data.toJSONString(), Map.class);
        Map parkingLotMap = maps.get(0);
        VehcParkingLot vehcParkingLot = new VehcParkingLot();
        vehcParkingLot.setCarSpotNum((Integer) parkingLotMap.get("CarNum"));
        vehcParkingLot.setName((String) parkingLotMap.get("ParkName"));
        vehcParkingLot.setThirdParkId((String) parkingLotMap.get("ParkingID"));
        return vehcParkingLot;
    }*/

    @Override
    public VehcParkingLot getParkingLotInfo(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        HashMap<String, Object> newMap = new HashMap<>();

        newMap.put("ParkingId", paramMap.get("parkId"));
        newMap.put("AccessCode", accessCode);
        newMap.put("SignType", signType);
        newMap.put("CompanyId",companyId );
        newMap.put("BusinessCode","ParkinfoGetList_001" );
        Map<String, String> map = SignUtils.mapWithSignature(newMap, appSecret);
        String json = HttpUtils.post(host, map);
        //解析json
        JSONArray data = JSONObject.parseObject(json).getJSONArray("Data");
        List<Map> maps = JSONArray.parseArray(data.toJSONString(), Map.class);
        Map parkingLotMap = maps.get(0);
        VehcParkingLot vehcParkingLot = new VehcParkingLot();
        vehcParkingLot.setCarSpotNum((Integer) parkingLotMap.get("CarNum"));
        vehcParkingLot.setName((String) parkingLotMap.get("ParkName"));
        vehcParkingLot.setThirdParkId((String) parkingLotMap.get("ParkingID"));
        return vehcParkingLot;
    }

    @Override
    public List<VehcArea> getParkingLotArea(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        HashMap<String, Object> newMap = new HashMap<>();
        newMap.put("ParkingId", paramMap.get("parkId"));
        newMap.put("AccessCode", accessCode);
        newMap.put("SignType", signType);
        newMap.put("CompanyId",companyId );
        newMap.put("BusinessCode","AreaGetList_001" );
        //areaDTO.setParkingId(areaDTO.getParkId()).setAccessCode(accessCode).setSignType(signType).setCompanyId(companyId).setBusinessCode("AreaGetList_001");
        Map<String, String> map = SignUtils.mapWithSignature(newMap, appSecret);
        String json = HttpUtils.post(host, map);
        //解析json
        JSONArray data = JSONObject.parseObject(json).getJSONArray("Data");
        List<Map> maps = JSONArray.parseArray(data.toJSONString(), Map.class);
        List<VehcArea> list = new ArrayList<>();
        //根据第三方parkId查询该车场信息
        String parkId = (String) paramMap.get("parkId");
        VehcParkingLot parkingLotFromDB = vehcParkingLotDao.selectOne(new QueryWrapper<VehcParkingLot>().eq("third_park_id", parkId));

        maps.forEach(a->{
            String thirdAreaId = (String) a.get("AreaID");
            String areaName = (String)a.get("AreaName");
            Integer carNum = (Integer)a.get("CarNum");
            VehcArea vehcArea = new VehcArea();
            vehcArea.setParkingLotId(parkingLotFromDB.getId()).setThirdAreaId(thirdAreaId).setName(areaName).setCarSpotNum(carNum);
            list.add(vehcArea);
        });
        return list;
    }

    @Override
    public List<VehcPassage> getPassageList(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        HashMap<String, Object> newMap = new HashMap<>();
        newMap.put("ParkingId", paramMap.get("parkId"));
        newMap.put("AccessCode", accessCode);
        newMap.put("SignType", signType);
        newMap.put("CompanyId",companyId );
        newMap.put("BusinessCode","GateGetList_001" );
        //passageDTO.setParkingId(passageDTO.getParkId()).setAccessCode(accessCode).setSignType(signType).setCompanyId(companyId).setBusinessCode("GateGetList_001");
        Map<String, String> map = SignUtils.mapWithSignature(newMap, appSecret);
        String json = HttpUtils.post(host, map);
        //解析json
        JSONArray data = JSONObject.parseObject(json).getJSONArray("Data");
        List<Map> maps = JSONArray.parseArray(data.toJSONString(), Map.class);
        ArrayList<String> thirdAreaIdList = new ArrayList<>();
        List<VehcPassage> list = new ArrayList<>();
        maps.forEach(n->{
            VehcPassage vehcPassage = new VehcPassage();
            String thirdPassageId = (String) n.get("GateID");
            String gateName = (String)n.get("GateName");
            Integer ioState = (Integer) n.get("IoState");
            String thirdAreaId = (String) n.get("AreaID");
            if (ioState==1) {
                vehcPassage.setType(PassageTypeEnum.ENTRANCE);
            }else if (ioState==2){
                vehcPassage.setType(PassageTypeEnum.EXIT);
            }
            thirdAreaIdList.add(thirdAreaId);
            vehcPassage.setName(gateName).setThirdPassageId(thirdPassageId).setThirdAreaId(thirdAreaId);
            list.add(vehcPassage);
        });
        //根据thirdAreaIdList查询数据库
        String parkId = (String) paramMap.get("parkId");
        List<VehcArea> listFromDB = vehcAreaDao.selectList(new QueryWrapper<VehcArea>().in("third_area_id", thirdAreaIdList));
        VehcParkingLot parkingLotFromDB = vehcParkingLotDao.selectOne(new QueryWrapper<VehcParkingLot>().eq("third_park_id", parkId));
        list.forEach(l->{
            listFromDB.forEach(lfDB->{
                StringBuilder builder = new StringBuilder();
                if (l.getThirdAreaId().equals(lfDB.getThirdAreaId())) {
                    l.setPlace(builder.append(parkingLotFromDB.getName()).append("-").append(lfDB.getName()).toString());
                    l.setAreaOrgId(lfDB.getOrgId());
                    l.setAreaId(lfDB.getId());
                }
            });
            l.setParkingLotId(parkingLotFromDB.getId());

        });

        return list;
    }

    @Override
    public List<Device> getParkingLotDevice(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        //暂无接口
        return null;
    }

    @Override
    public Map addCar(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
/*        paramMap.put("ParkingId", paramMap.get("parkId"));
        paramMap.put("AccessCode", accessCode);
        paramMap.put("SignType", signType);
        paramMap.put("CompanyId",companyId );
        paramMap.put("BusinessCode","GateGetList_001" );
        String plateNumber = carDTO.getPlateNoInfo().get(0).getPlateNo();
        String ownerName = carDTO.getUserName();
        String mobile = carDTO.getCardInfo().getTel();
        Integer cardChargeRuleId = carDTO.getCardChargeRuleId();
        //通过cardChargeRuleId查询所需的cardTypeId
        VehcCardChargeRule vehcCardChargeRule = vehcCardChargeRuleDao.selectById(cardChargeRuleId);
        String cardTypeId = vehcCardChargeRule.getChargeRuleCode();
        String beginTime = carDTO.getCarLotList().get(0).getBeginTime();
        String endTime = carDTO.getCarLotList().get(0).getEndTime();
        //判断车卡类型
        CardTypeEnum cardType = vehcCardChargeRule.getCardType();
        carDTO.setParkingId(carDTO.getParkId()).setAccessCode(accessCode).setSignType(signType).setCompanyId(companyId);
        if (cardType.equals(CardTypeEnum.MONTH)) {
            carDTO.setBusinessCode("MonthCarAdd_001");

        }else if (cardType.equals(CardTypeEnum.STORE)){
            carDTO.setBusinessCode("StoreCarAdd_001");

        }
        //设置新增车的必要参数
        carDTO.setPlateNumber(plateNumber).setOwnerName(ownerName).setMobile(mobile).setCardTypeId(cardTypeId).setBeginDate(beginTime).setEndDate(endTime);

        Map<String, String> map = SignUtils.mapWithSignature(carDTO, appSecret);
        String json = HttpUtils.post(host, map);
        Object data = JSONObject.parseObject(json).get("Data");
        Map dataMap = JSON.parseObject(JSON.toJSONString(data), Map.class);
        String grantId = (String)dataMap.get("GrantID");
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("thirdId",grantId);*/
        return null;
    }

    @Override
    public void update(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {

    }

    @Override
    public Map queryCarInfo(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        return null;
    }

    @Override
    public void delete(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {

    }

    @Override
    public List<Map> queryChargeWay(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        HashMap<String, Object> newMap = new HashMap<>();
        newMap.put("ParkingId", paramMap.get("parkId"));
        newMap.put("AccessCode", accessCode);
        newMap.put("SignType", signType);
        newMap.put("CompanyId",companyId );
        newMap.put("BusinessCode","CardTypeGetList_001" );
        Integer type = (Integer) paramMap.get("carType");
        Map<String, String> map = SignUtils.mapWithSignature(newMap, appSecret);
        String json = HttpUtils.post(host, map);
        //解析json
        JSONArray data = JSONObject.parseObject(json).getJSONArray("Data");
        List<Map> maps = JSONArray.parseArray(data.toJSONString(), Map.class);
        //博思高接口文档定义基础类型(0贵宾卡、1储值卡、2月卡、3临时卡)
        if (type.equals(0)) {
            //临时车
            maps = maps.stream().filter(m -> m.get("BaseTypeID").equals(3)).collect(Collectors.toList());
        }else if(type.equals(1)){
            //免费车，对应vip
            maps = maps.stream().filter(m -> m.get("BaseTypeID").equals(0)).collect(Collectors.toList());

        }else if(type.equals(2)){
            //免费车，对应vip
            maps = maps.stream().filter(m -> m.get("BaseTypeID").equals(2)).collect(Collectors.toList());

        }else if(type.equals(3)){
            //免费车，对应vip
            maps = maps.stream().filter(m -> m.get("BaseTypeID").equals(1)).collect(Collectors.toList());

        }
        List<Map> resultList = new ArrayList<>();
        maps.forEach(m->{
            Map<Object, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("id",m.get("CardTypeID"));
            objectObjectHashMap.put("ruleName",m.get("CardTypeName"));
            objectObjectHashMap.put("amount",m.get("Amount"));
            resultList.add(objectObjectHashMap);
        });
        return resultList;
    }

    @Override
    public void recharge(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {

    }

    @Override
    public Map tempParkFeeQuery(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        return null;
    }

    @Override
    public Map tempParkRecharge(Map<String, Object> paramMap, SupplierConfigDTO supplierConfigDTO) {
        return null;
    }


}

